﻿namespace Vinno.WMS.Pack.Extensions
{
    public static class MaterialExtensions
    {
        /// <summary>
        /// 将节点对象集合转换为树形节点对象集合
        /// </summary>
        /// <param name="nodes">节点对象集合</param>
        /// <param name="excludeNull">排除Null值对象</param>
        /// <param name="removeDuplicate">去除重复对象</param>
        /// <returns></returns>
        public static ICollection<MaterialCategoryTreeNodeDto> ToTreeNodes(this ICollection<MaterialCategoryNodeDto> nodes, bool excludeNull = true, bool removeDuplicate = true)
        {
            List<MaterialCategoryTreeNodeDto> treeNodes = new();
            if (nodes == null)
            {
                return treeNodes;
            }
            List<MaterialCategoryNodeDto> nodeList = nodes.ToList();
            if (excludeNull)
            {
                nodeList = nodeList.Where(o => o != null).ToList();
            }
            if (removeDuplicate)
            {
                nodeList = nodeList.Distinct().ToList();
            }

            var parentNodeList = nodeList.Where(m => !m.ParentId.HasValue || !nodeList.Exists(o => Equals(o.Id, m.ParentId))).ToList();
            foreach (var parentNode in parentNodeList)
            {
                var treeNode = parentNode.MapTo<MaterialCategoryNodeDto, MaterialCategoryTreeNodeDto>();
                treeNode.Children = GetTreeNodes(treeNode, nodeList);
                treeNodes.Add(treeNode);
            }
            return treeNodes;
        }

        /// <summary>
        /// 递归树形节点对象集合，将普通List转换为树形数据结构 RecursionTreeNode
        /// </summary>
        /// <param name="treeNode">树形节点数据</param>
        /// <param name="nodes">节点对象集合</param>
        /// <returns></returns>
        private static List<MaterialCategoryTreeNodeDto> GetTreeNodes(MaterialCategoryTreeNodeDto treeNode, List<MaterialCategoryNodeDto> nodes)
        {
            List<MaterialCategoryTreeNodeDto> treeNodes = new();
            var children = nodes.Where(o => treeNode.Id == o.ParentId).OrderBy(m => m.Id).ToList();
            if (children?.Count > 0)
            {
                foreach (var child in children)
                {
                    var childTreeNode = child.MapTo<MaterialCategoryNodeDto, MaterialCategoryTreeNodeDto>();
                    if (nodes.Exists(m => Equals(m.ParentId, childTreeNode.Id)))
                    {
                        childTreeNode.Children = GetTreeNodes(childTreeNode, nodes);
                    }
                    treeNodes.Add(childTreeNode);
                }
            }
            return treeNodes;
        }

    }
}
